<template>
    <div class="app-container">
        <div style="text-align: center;margin-bottom: 30px">
            管理员{{ createStatus ? '新增' : '更新' }}
        </div>
        <el-row :gutter="10">
            <el-form :model="adminForm" ref="adminForm" :rules="adminFormRules" label-width="100px">
                <el-col :xs="24" :sm="24" :md=5 :lg="5" :xl="5">
                    <el-form-item label="头像" prop="avatar">
                        <el-upload class="avatar-uploader"
                                :headers="headers"
                                :action="uploadImg"
                                :data="{type:'avatar'}"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="adminForm.avatar&& imgFlag == false" :src="adminForm.avatar" class="avatar">
                            <i v-else-if="!adminForm.avatar&& imgFlag == false"
                               class="el-icon-plus avatar-uploader-icon"></i>
                            <el-progress v-if="imgFlag == true" type="circle" :percentage="imgUploadPercent" style="margin-top:30px;"></el-progress>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
                        <el-form-item label="用户名" prop="userName">
                            <el-input type="text" v-model="adminForm.userName" placeholder="请输入用户名"
                                      clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="adminForm.name" placeholder="请输入姓名" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
                        <el-form-item label="联系邮箱" prop="email">
                            <el-input type="text" v-model="adminForm.email" placeholder="请输入联系邮箱"
                                      clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
                        <el-form-item label="联系电话" prop="mobile">
                            <el-input type="text" v-model="adminForm.mobile" placeholder="请输入联系电话"
                                      clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
                        <el-form-item label="省市县" prop="userLocal">
                            <city-select :local="adminForm.userLocal" v-on:handleChange="getCity"></city-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
                        <el-form-item label="详细地址" prop="address">
                            <el-input type="text" v-model="adminForm.address" placeholder="请输入详细地址"
                                      clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
                        <el-form-item label="用户状态" prop="status">
                            <el-switch
                                    v-model="adminForm.status"
                                    active-color="#13ce66"
                                    inactive-color="#ff4949">
                            </el-switch>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
                        <el-form-item label="性别" prop="sex">
                            <el-radio-group v-model="adminForm.sex">
                                <el-radio :label="1">男</el-radio>
                                <el-radio :label="2">女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
                        <el-form-item  label="所属主体" prop="flagId">
                            <el-select v-model="adminForm.flagId" placeholder="请选择主体" style="width: 100%" clearable @clear="clearInput1()">
                                <el-option v-for="(item,index) in enterpriseDominantList" :key="index"  :value="item.ucId" :label="item.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
                        <el-form-item label="所属角色" prop="roleId">
                            <el-select v-model="adminForm.roleId"  placeholder="请选择角色" style="width: 100%">
                                <el-option v-for="(item,index) in roleList" :key="index" :value="item.ucId"
                                           :label="item.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
                        <el-form-item v-if="createStatus" label="密码" prop="password">
                            <el-input type="password" v-model="adminForm.password" placeholder="请输入密码"
                                      clearable></el-input>
                        </el-form-item>
                        <el-form-item v-else label="重置密码" prop="password">
                            <el-switch
                                    style="width: 50%"
                                    v-model="adminForm.resetPassword"
                                    active-color="#13ce66"
                                    inactive-color="#ff4949"
                                    active-text="重置"
                                    inactive-text="不重置"
                                    @change="resetPassword">
                            </el-switch>
                            <el-input v-if="adminForm.resetPassword" style="width: 50%" type="password"
                                      v-model="adminForm.password" placeholder="请输入新密码" clearable></el-input>
                        </el-form-item>
                    </el-col>

                </el-col>
            </el-form>
        </el-row>
        <div slot="footer" style="text-align: center" class="dialog-footer">
            <el-button @click="cancelAdmin">取 消</el-button>
            <el-button :loading="addLoading" v-if="createStatus" type="primary" @click="createAdmin">创 建</el-button>
            <el-button :loading="addLoading" v-else type="primary" @click="updateAdmin">修 改</el-button>
        </div>
    </div>
</template>

<script>
import {addInAdmin, updateInUser, getInUserVo} from "@/api/enterprise";
import {uploadImg} from "@/api/common";
import {getToken} from "@/utils/auth";
import {getInRoleList} from "@/api/role";
import CitySelect from "@/components/citySelect/index.vue";
import {getInEnterpriseDominantList} from "@/api/enterpriseDominant";

export default {
    name: "adminForm",
    components: {CitySelect},
    data() {
        let checkData =(rule, value, callback) =>{
            if (value === '') {
                callback(new Error('请输入用户名'))
            } else if (/[\u4E00-\u9FA5]/g.test(value)) {
                callback(new Error('用户名不能输入汉字!'))
            } else {
                callback()
            }
        };
        let checkPhone = (rule, value, callback) => {
            const reg = /^0?(13[0-9]|15[012356789]|18[0-9]|14[578]|16[6]|17[035768]|19[19])[0-9]{8}$/
            if ( reg.test(value) ) {
                return callback();
            }
            callback('请输入合法的手机号');
        };
        return {
            uploadImg,
            adminForm: {
                sex: 1,
                status: true,
                type:0,

            },
            adminFormRules: {
                address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
                userName: [{ validator:checkData,required: true, trigger: 'blur' }],
                mobile: [{  validator:checkPhone,required: true, trigger: 'blur' }],
                userLocal: [{ required: true, message: '省市县不能为空', trigger: 'blur' }],
                password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
                flagId: [{ required: true, message: '所属主体不能空', trigger: 'change' }],
                roleId: [{ required: true, message: '所属角色不能为空', trigger: 'change' }],
            },
            imgFlag: false,
            imgUploadPercent: 0,
            addLoading: false,
            roleList: [],
            enterpriseDominantList:[],
        }
    },
    computed: {
        createStatus() {
            return this.$route.params.ucId == '0'
        },
        headers() {
            return {
                'Authorization': getToken()
            }
        },
    },
    created() {
        this.getInRoleList()
       this.getInEnterpriseDominantList()
        if (!this.createStatus) {
            let ucId = this.$route.params.ucId
            this.getInAdminVo(ucId)
        }
    },
    methods: {
        getInAdminVo(val) {
            getInUserVo({ucId: val}).then(res => {
                console.log(res.data)
                this.adminForm = res.data
                this.adminForm.userLocal = [this.adminForm.province, this.adminForm.city, this.adminForm.county]

            }).catch(res => {

            })
        },
        cancelAdmin() {
          window.history.back()
        },
        createAdmin() {
            this.addLoading = true
            this.$refs['adminForm'].validate(valid => {
                if (valid) {
                    addInAdmin(this.adminForm).then(res => {
                        this.addLoading = false
                        this.$notify.success({
                            title: '成功',
                            message: "添加管理员成功"
                        })
                        this.cancelAdmin()
                    }).catch(res => {
                        this.addLoading = false
                        this.$notify.error({
                            title: '失败',
                            message: res.msg
                        })
                    })
                } else {
                    this.addLoading = false
                    console.log("表单验证不通过")
                }
            })
        },
        updateAdmin() {
            this.addLoading = true
            this.$refs['adminForm'].validate(valid => {
                if (valid) {
                    updateInUser(this.adminForm).then(res => {
                        this.addLoading = false
                        this.$notify.success({
                            title: '成功',
                            message: "更新管理员成功"
                        })
                        this.cancelAdmin()
                    }).catch(res => {
                        this.addLoading = false
                        this.$notify.error({
                            title: '失败',
                            message: res.msg
                        })
                    })
                } else {
                    this.addLoading = false
                    console.log("表单验证不通过")
                }
            })
        },
        //重置密码操作
        resetPassword(val) {
            if (val) {
                this.adminForm.password = null
            }
        },
        handleAvatarSuccess(res, file) {
            //图片上传成功
            console.log(res)
            this.imgFlag = false;
            this.adminForm.avatar = res.data;
        },
        handleAvatarFail(error) {
            console.log(error)
        },
        uploadImgProcess(event, file, fileList) {
            this.imgFlag = true;
            this.imgUploadPercent = file.percentage.toFixed(0);
        },
        beforeAvatarUpload(file) {
            console.log(file)
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG、png格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        getInRoleList() {
            getInRoleList({deleted: false}).then(res => {
              console.log(res)
                this.roleList = res.data
            }).catch(error => {

            })
        },
        //选择位置信息
        getCity(val) {
            this.adminForm.userLocal = val
            this.adminForm.province = val[0]
            this.adminForm.city = val[1]
            this.adminForm.county = val[2]
        },
        getInEnterpriseDominantList(){
            getInEnterpriseDominantList({deleted:false}).then(res=>{
                this.enterpriseDominantList = res.data
            }).catch(error=>{

            })
        }
    }
}
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 149px;
    height: 149px;
    line-height: 149px;
    text-align: center;
}

.avatar {
    width: 149px;
    height: 149px;
    display: block;
}
</style>
